#!/bin/bash

#
# Copyright 2010-2025 JetBrains s.r.o. and Kotlin Programming Language contributors.
# Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
#

# Script to convert Space CODEOWNERS to matching GitHub CODEOWNERS
# 1. Copies CODEOWNERS file to .github
# 2. Replaces team owners such as "Kotlin Build Infrastructure" with their GitHub team equivalent for GitHub CODEOWNERS
# 3. If given Space team is in "codeowners-virtual-team-mapping.json", "virtualMembers" field is used instead of the GitHub team

# Make the script execution relative to project root
PARENT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" || exit 1 ; pwd -P )
cd "$PARENT_PATH" || exit 1

# Path to the input and output files
GITHUB_CODEOWNERS_FILE="../.github/CODEOWNERS"
SPACE_CODEOWNERS_FILE="../.space/CODEOWNERS"
TEAM_MAPPING_FILE="../.space/codeowners-virtual-team-mapping.json"

# Check if jq is installed
if ! command -v jq &> /dev/null; then
    echo "Error: jq is not installed. Please install jq to run this script."
    exit 1
fi

# Check if the required files exist
if [ ! -f "$SPACE_CODEOWNERS_FILE" ]; then
    echo "Error: $SPACE_CODEOWNERS_FILE does not exist"
    exit 1
fi

if [ ! -f "$TEAM_MAPPING_FILE" ]; then
    echo "Error: $TEAM_MAPPING_FILE does not exist"
    exit 1
fi

# Create a temporary file for GitHub CODEOWNERS file
GITHUB_TMP_FILE=$(mktemp)

# Header text for generated files
HEADER="# Auto-generated file. DO NOT EDIT!
# Generated by '.space/generate-github-codeowners.sh' script

# This file is checked by org.jetbrains.kotlin.code.GitHubOwnersTest
# Correctness can be also verified by opening it on your branch/commit on GitHub where a banner with information \`This CODEOWNERS file is valid.\` should be displayed
"

# Process the OWNERS file line by line
while IFS= read -r line; do
    # Skip comment lines from Space CODEOWNERS as they are not relevant for the GitHub file
    if [[ "$line" == \#* ]]; then
        continue
    fi

    # Skip empty lines but preserve them in the output
    if [[ -z "$line" ]]; then
        echo "$line" >> "$GITHUB_TMP_FILE"
        continue
    fi

    # Start with the original line
    processed_line="$line"

    # Extract all team names in quotes and process them
    while [[ "$processed_line" =~ \"([^\"]*)\" ]]; do
        team_pattern="\"${BASH_REMATCH[1]}\""
        team_name="${BASH_REMATCH[1]}"

        # Use jq to check if the team has virtual members and extract them
        virtual_members=$(jq -r --arg team "$team_name" '.[] | select(.spaceTeam == $team) | .virtualMembers | join(" ")' "$TEAM_MAPPING_FILE")

        # If team has virtual members, use them, otherwise use GitHub team name
        if [[ -n "$virtual_members" ]]; then
            # Replace the team name with its virtual members
            processed_line="${processed_line//$team_pattern/$virtual_members}"
        else
            # Construct GitHub team name from team_name (lowercase, replace whitespaces with dash, prepend "@JetBrains/")
            github_team="@JetBrains/$(echo "$team_name" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')"
            # Replace the team name with its GitHub team equivalent
            processed_line="${processed_line//$team_pattern/$github_team}"
        fi
    done

    echo "$processed_line" >> "$GITHUB_TMP_FILE"
done < "$SPACE_CODEOWNERS_FILE"

# Copy the processed file to the GitHub destination with header
printf "$HEADER" > "$GITHUB_CODEOWNERS_FILE"
cat "$GITHUB_TMP_FILE" >> "$GITHUB_CODEOWNERS_FILE"

# Clean up
rm "$GITHUB_TMP_FILE"

echo "Conversion completed. CODEOWNERS file created at $GITHUB_CODEOWNERS_FILE"
